<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SSE Example</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        #events {
            white-space: pre-line;
            border: 1px solid #ccc;
            padding: 10px;
            height: 200px;
            overflow-y: auto;
        }
    </style>
</head>
<body>
<h1>Server-Sent Events Example</h1>
<div id="events"></div>

<script>
    // 创建一个新的 EventSource 对象，连接到 SSE 端点
    const eventSource = new EventSource('http://localhost:8080/sse/1');

    // 监听 'message' 事件，当有新的消息到达时触发
    eventSource.onmessage = function(event) {
        const eventsDiv = document.getElementById('events');
        // 在页面上显示新消息
        eventsDiv.textContent += event.data + '\n';
    };

    // 可选：监听 'open' 事件，当连接打开时触发
    eventSource.onopen = function(event) {
        console.log('SSE connection opened.');
    };

    // 可选：监听 'error' 事件，当连接出错时触发
    eventSource.onerror = function(event) {
        if (eventSource.readyState === EventSource.CLOSED) {
            console.log('SSE connection closed.');
        } else {
            console.error('SSE error:', event);
        }
    };
</script>
</body>
</html>